package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.NearUserVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.RecommendUserVo;
import com.itheima.vo.VisitorVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MakeFriendManager {

    @DubboReference
    private RecommendUserService recommendUserService;

    @DubboReference
    private UserInfoService userInfoService;

    // 今日佳人
    public ResponseEntity findTodayBest() {
        // 1.获取线程内toUserId
        Long toUserId = UserHolder.get().getId();
        // 2.调用rpc
        RecommendUser recommendUser = recommendUserService.findTodayBast(toUserId);
        // 3.封装recommentUserVo
        RecommendUserVo vo = new RecommendUserVo();
        // 设置userInfo
        vo.setUserInfo(userInfoService.findById(recommendUser.getUserId())); // 佳人id
        // 设置缘分值
        vo.setFateValue(recommendUser.getScore().longValue());
        // 4.返回vo
        return ResponseEntity.ok(vo);
    }

    // 推荐用户
    public ResponseEntity findReommendUserVoByPage(Integer pageNum, Integer pageSize) {
        // 1.获取线程内toUserId
        Long toUserId = UserHolder.get().getId();
        // 2.调用rpc查询
        PageBeanVo pageBeanVo = recommendUserService.findRecommendUserByPage(toUserId, pageNum, pageSize);
        // 3.封装voList
        // 3-1 声明voList
        List<RecommendUserVo> voList = new ArrayList<>();
        // 3-2 获取recommentUserList
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();
        // 3-3 遍历
        if (CollectionUtil.isNotEmpty(recommendUserList)) {
            for (RecommendUser recommendUser : recommendUserList) {
                // 创建vo
                RecommendUserVo vo = new RecommendUserVo();
                // 先设置userInfo
                vo.setUserInfo(userInfoService.findById(recommendUser.getUserId()));
                // 再设置缘分值
                vo.setFateValue(recommendUser.getScore().longValue());

                // 添加到集合
                voList.add(vo);
            }
        }
        // 4.将voLiset设置到分页对象
        pageBeanVo.setItems(voList);
        // 5.返回分页对象
        return ResponseEntity.ok(pageBeanVo);
    }

    // 推荐用户详情
    public ResponseEntity findPersonalInfo(Long jiarenId) {
        // 1.获取线程内toUserId
        Long toUserId = UserHolder.get().getId();
        // 2.调用rpc查询
        RecommendUser recommendUser = recommendUserService.findPersonalInfo(toUserId, jiarenId);
        // 解决自己、好友查不到 推荐用户问题
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(jiarenId);
            recommendUser.setScore(100d);
        }

        // 3.封装vo
        RecommendUserVo vo = new RecommendUserVo();
        // 先设置userInfo
        vo.setUserInfo(userInfoService.findById(recommendUser.getUserId()));
        // 再设置缘分值
        vo.setFateValue(recommendUser.getScore().longValue());
        // 4.返回vo
        return ResponseEntity.ok(vo);
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private VisitorService visitorService;

    // 最近访客
    public ResponseEntity findVisitors() {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.获取上次查询时间
        String lastAccessTime = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);
        // 3.判断
        List<VisitorVo> voList = new ArrayList<>();
        if (StrUtil.isNotEmpty(lastAccessTime)) {
            // 查询访客信息
            List<Visitor> visitorList = visitorService.findVisitors(userId, Long.parseLong(lastAccessTime));
            // 4.封装voList
            //  遍历
            if (CollectionUtil.isNotEmpty(visitorList)) {
                for (Visitor visitor : visitorList) {
                    // 创建vo
                    VisitorVo vo = new VisitorVo();
                    // 先设置userInfo
                    vo.setUserInfo(userInfoService.findById(visitor.getVisitorUserId()));
                    // 再设置缘分值
                    vo.setFateValue(visitor.getScore().longValue());
                    // 添加到集合
                    voList.add(vo);
                }
            }
        }
        // 5.记录本次查询时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME + userId, String.valueOf(System.currentTimeMillis()));

        // 6.返回voList
        return ResponseEntity.ok(voList);
    }

    @DubboReference
    private UserLocationService userLocationService;

    // 上报地理位置
    public void saveLocation(Double longitude, Double latitude, String addrStr) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc保存
        userLocationService.saveLocation(longitude, latitude, addrStr, userId);
    }

    // 搜附近
    public ResponseEntity searchNearUser(String gender, Long distance) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.调用rpc查询
        List<Long> nearUserIdList = userLocationService.searchNearUser(userId, distance);
        // 3.遍历
        List<NearUserVo> voList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(nearUserIdList)) {
            for (Long nearUserId : nearUserIdList) {
                // 排除自己
                if (userId == nearUserId) {
                    continue;
                }
                // 查询userInfo
                UserInfo userInfo = userInfoService.findById(nearUserId);
                // 排除前端条件的异性
                if (!StrUtil.equals(gender, userInfo.getGender())) {
                    continue;
                }
                // 封装vo
                NearUserVo vo = new NearUserVo();
                vo.setUserId(userInfo.getId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                // 添加到集合
                voList.add(vo);
            }
        }
        // 4.返回voList
        return ResponseEntity.ok(voList);
    }

    @DubboReference
    private QuestionService questionService;

    // 聊一下（查看陌生人问题）
    public ResponseEntity strangerQuestions(Long jiarenId) {
        // 1.调用rpc查询
        Question question = questionService.findByUserId(jiarenId);
        // 2 .空判断
        if (question==null) {
            question = new Question();
        }
        // 3.返回问题内容
        return   ResponseEntity.ok(question.getStrangerQuestion());
    }
}
